package middleware

import (
	"mpps/tools/auth"
	"mpps/tools/common"
	"mpps/tools/config"
	"mpps/web/models"
	"net/http"
	"regexp"
	"strings"

	"github.com/asim/go-micro/v3/logger"
	"github.com/gin-gonic/gin"
)

func WebAuthMiddleWare() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.Request.Header.Get("token")
		url := ctx.Request.RequestURI
		logger.Infof("url=%v", url)
		// 不校验
		pattern := strings.Join(config.WebTokenFilter, "|")
		if ok, _ := regexp.MatchString(pattern, url); ok {
			ctx.Next()
			return
		}
		if len(token) <= 0 {
			models.WriteHttpFail(ctx, common.ErrAuth)
			ctx.Abort()
			return
		}
		// 校验token
		if claims, err := auth.ParseToken(token, false); err == nil {
			logger.Infof("claims=%v", claims)
			ctx.Next()
			return
		} else {
			models.WriteHttpFail(ctx, common.ErrAuth)
			ctx.Abort()
			return
		}
	}
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", origin) // 可将将 * 替换为指定的域名
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, token")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
